package org.androidtown.ui.pager;

import java.util.Calendar;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;

public class MainActivity extends FragmentActivity {
    ViewPager monthPage;
    private static final int PAGE_MIDDLE = 1;
    private int mSelectedPageIndex = 1;
    public Calendar curMonth;
    InfinitePagerAdapter monthPageAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final CalendarView[] fragList = new CalendarView[3];
        curMonth = Calendar.getInstance();
        Calendar prevMonth, nextMonth;
        prevMonth = (Calendar) curMonth.clone();
        nextMonth = (Calendar) curMonth.clone();
        prevMonth.set(Calendar.MONTH, prevMonth.get(Calendar.MONTH) - 1);
        nextMonth.set(Calendar.MONTH, nextMonth.get(Calendar.MONTH) + 1);
                
        fragList[0] = CalendarView.newInstance(prevMonth);
        fragList[1] = CalendarView.newInstance(curMonth);
        fragList[2] = CalendarView.newInstance(nextMonth);

        monthPage = (ViewPager) findViewById(R.id.pager);
        monthPageAdapter = new InfinitePagerAdapter(getSupportFragmentManager(), fragList);
        monthPage.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrollStateChanged(int arg0) {
                // TODO Auto-generated method stub
                if (arg0 == ViewPager.SCROLL_STATE_IDLE) {
                    if (mSelectedPageIndex < PAGE_MIDDLE) {
                        fragList[0].onPreviousMonth();
                        fragList[1].onPreviousMonth();
                        fragList[2].onPreviousMonth();
                    } else if (mSelectedPageIndex > PAGE_MIDDLE) {
                        fragList[0].onNextMonth();
                        fragList[1].onNextMonth();
                        fragList[2].onNextMonth();
                    }
                    monthPage.setCurrentItem(1, false);
                }
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onPageSelected(int arg0) {
                // TODO Auto-generated method stub
                mSelectedPageIndex = arg0;
            }
        });
        monthPage.setAdapter(monthPageAdapter);
        monthPage.setCurrentItem(1, false);
    }
}